package com.qyhl.webtv.commonlib.utils;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import androidx.core.content.FileProvider;

import android.util.Log;
import android.view.View;

import com.google.gson.Gson;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.CommonDialog;
import com.qyhl.webtv.basiclib.utils.dialog.UpdateDialog;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.qyhl.webtv.basiclib.utils.network.callback.SimpleCallBack;
import com.qyhl.webtv.basiclib.utils.network.exception.ApiException;
import com.qyhl.webtv.commonlib.R;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.PathConfigConstant;
import com.qyhl.webtv.commonlib.entity.VersionBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.service.VersionService;

import java.io.File;

/**
 * Created by Administrator on 2018/4/18.
 */

public class UpdateAPK {
    private Activity activity;
    private int versionCode;
    private File apkFile, newApkFile;
    private final static String PATH = Environment.getExternalStorageDirectory().getPath() + PathConfigConstant.Apk;
    private OnStateListener listener;
    private boolean isNeedNewToast;

    public UpdateAPK(Activity activity, boolean isNeedNewToast) {
        this.activity = activity;
        this.isNeedNewToast = isNeedNewToast;
        //获取当前版本号
        try {
            PackageManager manager = activity.getPackageManager();
            PackageInfo info = manager.getPackageInfo(activity.getPackageName(), 0);
            versionCode = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void checkUpdate() {
        if (!PathConfigConstant.isLoading) {

            String url = CommonUtils.getInstance().getAppConfigUrl() + "App_Config/version/check";

            EasyHttp.get(url)
                    .params("siteId", String.valueOf(CommonUtils.getInstance().getSite()))
                    .execute(new SimpleCallBack<String>() {
                        @Override
                        public void onError(ApiException e) {

                        }

                        @Override
                        public void onSuccess(String s) {
                            VersionBean versionBean = new Gson().fromJson(s,VersionBean.class);
                            if (versionBean != null && versionBean.getData() != null) {
                                if (versionCode < versionBean.getData().getCode()) {
                                    listener.getData(versionBean.getData());
                                    versionSuccess(versionBean.getData());
                                } else {
                                    if (isNeedNewToast) {
                                        listener.onState("已经是最新版本了！");
                                    }
                                }
                            } else {
                                if (isNeedNewToast) {
                                    listener.onState("已经是最新版本了！");
                                }
                            }
                        }
                    });

        } else {
            listener.onState("正在下载中...");
        }
    }

    public void versionSuccess(final VersionBean.DataBean bean) {
        if (!PathConfigConstant.isLoading) {
            //判断当前版本是否小于服务器版本
            if (versionCode < bean.getCode() && activity != null && !activity.isFinishing()) {
                //判断是否已经下载
                if (isDownLoad(bean.getCode())) {
                    CommonDialog.Builder builder = new CommonDialog.Builder(activity)
                            .setTitle("安装提示", R.color.global_black_lv1)
                            .setMessage("安装包已经下载，是否立即安装？", R.color.global_black_lv2)
                            .setPositiveButton("立即安装", v -> installApk(), R.color.global_base)
                            .setNegativeButton("以后再说", view -> {
                                if (bean.getIsForceUpgrade() == 1) {
                                    activity.finish();
                                }
                            }, R.color.global_gray_lv2);
                    if (bean.getIsForceUpgrade() == 1) {
                        builder.setCancelable(false);
                        builder.setCanceledOnTouchOutside(false);
                    }
                    builder.show();
                } else {
                    if (isNeedNewToast) {
                        CommonDialog.Builder builder = new CommonDialog.Builder(activity)
                                .setTitle("发现新版本" + bean.getVersionName(), R.color.global_black_lv1)
                                .setMessage("是否立即更新，体验最新版本？", R.color.global_black_lv2)
                                .setPositiveButton("立即下载", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        downLoad(bean);
                                    }
                                }, R.color.global_base)
                                .setNegativeButton("以后更新", null, R.color.global_gray_lv2);
                        if (bean.getIsForceUpgrade() == 1) {
                            builder.setCancelable(false);
                            builder.setCanceledOnTouchOutside(false);
                        }
                        builder.show();
                    } else {
                        UpdateDialog.Builder builder = new UpdateDialog.Builder(activity)
                                .setIcon(R.mipmap.ic_launcher)
                                .setTitle(StringUtils.isEmpty(bean.getDownloadLead()) ? "" : bean.getDownloadLead(), R.color.global_black_lv1)
                                .setVersionCode(StringUtils.isEmpty(bean.getVersionName()) ? "" : bean.getVersionName(), R.color.global_black_lv4)
                                .setMessage(StringUtils.isEmpty(bean.getDetail()) ? "" : bean.getDetail(), R.color.global_black_lv2)
                                .setPositiveButton("立即下载", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        downLoad(bean);
                                    }
                                }, R.color.global_base)
                                .setNegativeButton("以后更新", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        ActionLogUtils.getInstance().onEvent(ActionConstant.NOUPDATE);
                                        if (bean.getIsForceUpgrade() == 1) {
                                            activity.finish();
                                        }
                                    }
                                }, R.color.global_gray_lv2);
                        if (bean.getIsForceUpgrade() == 1) {
                            builder.setCancelable(false);
                            builder.setCanceledOnTouchOutside(false);
                        }
                        builder.show();
                    }
                }
            } else {
                if (isNeedNewToast) {
                    listener.onState("已经是最新版本了！");
                }
            }
        } else {
            listener.onState("正在下载中...");
        }
    }

    /**
     * 判断是否已经下载了apk
     *
     * @return
     */
    private boolean isDownLoad(int code) {
        apkFile = new File(PATH);
        if (!apkFile.exists()) {
            apkFile.mkdirs();
        }

        File[] fList = apkFile.listFiles();
        //判断安装路径下是否有文件
        if (fList != null && fList.length > 0) {
            //遍历所有apk的版本号，当大于当前版本号，则有新的版本
            for (File file : fList) {
                if (file.getName().endsWith(".apk")) {
                    if (getVersionCodeFromApk(file.getAbsolutePath()) >= code) {
                        newApkFile = file;
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 获取apk的版本号
     *
     * @param path
     * @return
     */
    private int getVersionCodeFromApk(String path) {
        PackageManager pm = activity.getPackageManager();
        PackageInfo packInfo = pm.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);
        int versionCode;
        try {
            versionCode = packInfo.versionCode;
        } catch (Exception e) {
            versionCode = 0;
        }
        return versionCode;
    }

    /**
     * 下载新版本
     *
     * @param bean
     */
    private void downLoad(VersionBean.DataBean bean) {
        PathConfigConstant.isLoading = true;
        Intent intent = new Intent(activity, VersionService.class);
        intent.putExtra("loadUrl", bean.getUrl());
        intent.putExtra("versionName", bean.getVersionName());
        activity.startService(intent);
        ActionLogUtils.getInstance().onEvent(ActionConstant.UPDATE);
    }

    /**
     * 安装apk
     */
    private void installApk() {
        ActionLogUtils.getInstance().onEvent(ActionConstant.UPDATE);
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        String type = "application/vnd.android.package-archive";
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_VIEW);
            Uri uriForFile = FileProvider.getUriForFile(activity, activity.getPackageName() + ".provider", newApkFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(uriForFile, activity.getContentResolver().getType(uriForFile));
        } else {
            uri = Uri.fromFile(newApkFile);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(uri, type);
        }
        activity.startActivity(intent);
    }

    public UpdateAPK setListener(OnStateListener listener) {
        this.listener = listener;
        return this;
    }

    public interface OnStateListener {
        void onState(String msg);

        void getData(VersionBean.DataBean bean);
    }
}
